﻿using System.Linq;
using Daemon.Common;
using Daemon.Common.Helpers;
using Daemon.Infrustructure.EF;
using Daemon.Repository.EF.Enums;
using Daemon.Repository.Contract;
using Daemon.Model;
using System;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace Daemon.Repository.EF
{
	public class TakeAwayGoodTypeRepository : Repository<TakeAwayGoodType>, ITakeAwayGoodTypeRepository
	{
		private readonly ITakeAwayGoodRepository _takeAwayGoodRepository;

		protected override Expression<Func<TakeAwayGoodType, int>> PrimaryKeyExpression => r => r.Id;

		public TakeAwayGoodTypeRepository(ApiDBContent context, ITakeAwayGoodRepository takeAwayGoodRepository) : base(context)
		{
			_takeAwayGoodRepository = takeAwayGoodRepository;
		}

		protected override IEnumerable<TakeAwayGoodType> IncludeRelationships(IEnumerable<TakeAwayGoodType> entities, ApiDBContent db)
		{
			SetGoodList(entities);

			return base.IncludeRelationships(entities, db);
		}

		private void SetGoodList(IEnumerable<TakeAwayGoodType> entities)
		{
			if (!RouteParameterHelper.CheckRouteParameter(RelationshipNames, TakeAwayGoodTypeRelationShipEnum.GoodList))
			{
				return;
			}

			var goodTypeIds = entities.Select(r => r.Id).ToList();
			_takeAwayGoodRepository.SetRelationships(new List<Model.Entities.Relationship>() { new Model.Entities.Relationship() { Name = TakeAwayGoodRelationShipEnum.RuleInfo.ToString() } });
			var goodsDict = _takeAwayGoodRepository.IncludeRelationships(Context.TakeAwayGood.Where(r => goodTypeIds.Contains(r.GroupId))).ToList().GroupBy(r => r.GroupId).ToDictionary(r => r.Key, r => r.ToList());
			foreach (var entity in entities)
			{
				if (goodsDict.TryGetValue(entity.Id, out List<TakeAwayGood> goodList))
				{
					entity.GoodList = goodList;
				}
			}
		}
	}
}
